package com.aierjun.ani.utils.db;

import android.content.Context;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by aierJun on 2017/4/22.
 */
public class DBUtils {

    /**
     * 复制assets下数据库到data/data/packagename/databases
     * @param context
     * @throws IOException
     */
    public static void copyDBToDatabases(Context context) throws IOException {
        String DB_PATH = "/data/data/"+context.getPackageName()+"/databases/";
        String DB_NAME = "Area.db";
        String outFileName =  DB_PATH+DB_NAME;

        File file = new File(DB_PATH);
        if (!file.mkdirs()) {
            file.mkdirs();
        }

        if (new File(outFileName).exists()) {
            // 数据库已经存在，无需复制
            return;
        }

        InputStream myInput = context.getAssets().open(DB_NAME);
        OutputStream myOutput = new FileOutputStream(outFileName);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        myOutput.flush();
        myOutput.close();
        myInput.close();
    }
}
